package com.util;
import java.io.*;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import com.constant.Constant;

public class LogUtil {
	public static void log(String userName,String log)  {
		String fileName=userName+".log";
		
		//如果没有目录,则创建
		String logDir=Constant.LOG_PATH+"/"+userName;
		File dir=new File(logDir);
		if(dir.exists()==false) {
			dir.mkdirs();
		}
		
		String localLogPath=logDir+"/" +fileName;  // 通常: /tmp/admin/admin.log
		File destFile=new File(localLogPath);
		
		try {
			BufferedWriter bw=new BufferedWriter(new FileWriter(destFile,true));
			bw.write(log);
			bw.newLine();
			bw.flush();
			bw.close();
			
			//如果文件到达指定的大小则上传 (这里指定是5k)
			if(destFile.length()>1024*5) {
				URI uri=URI.create(Constant.HDFS_PATH);
						
				FileSystem fs=FileSystem.get(uri,Constant.CONF,Constant.HDFS_USER);
				String saveLogName=new SimpleDateFormat("yyyy-MM-dd").format(new Date())+"_"+System.currentTimeMillis()+".log";
				
				//这个方法,完成上传后,会自动删除本地文件
				fs.moveFromLocalFile(new Path(localLogPath), new Path("/"+userName+"/log/"+saveLogName));
			
				fs.close();
			}
			
		}catch(Exception ex) {
			ex.printStackTrace();
		}
	}
}
